package com.course.api.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.course.api.entity.Role;
import com.course.api.entity.RoleMenu;
import com.course.api.mapper.RoleMapper;
import com.course.api.mapper.RoleMenuMapper;
import com.course.api.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    RoleMenuMapper roleMenuMapper;

    @Override
    public List<RoleMenu> getRoleMenu(Long roleId) {
        QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        return roleMenuMapper.selectList(queryWrapper);
    }

    @Override
    public void setRoleMenu(Long roleId, List<Long> menuIds) {
        // 删除表中当前角色所有的菜单权限
        QueryWrapper<RoleMenu> roleMenuQueryWrapper = new QueryWrapper<>();
        roleMenuQueryWrapper.eq("role_id", roleId);
        roleMenuMapper.delete(roleMenuQueryWrapper);

        //将所有menuId添加表中
        menuIds.forEach(menuId -> {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenuMapper.insert(roleMenu);
        });
    }

    @Override
    public Long selectRoleId(String userType) {
        return roleMapper.selectRoleByDescription(userType);
    }
}
